/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"76DC328C-7E7E-4D2D-BEFE-480297FD3FBB",variableType:8}
 */
var fdolar = null;

/**
 * @type {String}
 *
 * @properties={typeid:35,uuid:"93063740-E385-4246-904B-B572715065B4"}
 */
var fLeyenda = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"1E6DA0AF-9CEB-416B-A540-D64D41159970",variableType:4}
 */
var fmoneda = null;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"CCE87559-6454-4C5C-8EA6-A9F9F8B3FB92",variableType:8}
 */
var ftotal = null;

/**
 * Callback method for when form is shown.
 *
 * @param {Boolean} [firstShow] form is shown first time after load
 * @param {JSEvent} [event] the event that triggered the action
 *
 * @properties={typeid:24,uuid:"F7088582-1A04-4685-BDF7-DA5396C52563"}
 */
function onShow(firstShow, event) {
	databaseManager.setAutoSave(false)
	controller.newRecord()
	globals.gvarios 	= 3
	fmoneda 			= 1
	ftotal 				= 0
	fLeyenda			= ""
    globals.gtotal_debe = 0
    globals.gtotal_haber = 0
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"50945365-0FA7-47F8-9973-8002FA977163"}
 */
function onAction_nuevo_item(event) {
	limbo_cab_to_limbo.newRecord()
	forms.limbo_carga_det.elements.cuentas_id.requestFocus()
	forms.limbo_carga_det.leyenda = fLeyenda
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"CFB34164-7D58-4BD1-8595-109D32608C2F"}
 * @AllowToRunInFind
 */
function onAction_confirmar(event) {
	var res = globals.DIALOGS.showQuestionDialog('','Actualiza el Asiento?','SI','NO')			    
	if (res == 'NO')
	{
		return
	}	
	var vAnio = fecha.getFullYear()
	var vMes = fecha.getMonth()+1
	/** @type {JSFoundSet<db:/contable/numcon>}*/
	var fs_numcon = databaseManager.getFoundSet('contable','numcon')
	
	fs_numcon.find()
	fs_numcon.anio 		= vAnio
	fs_numcon.mes  		= vMes
	fs_numcon.empresa 	= globals.gUservID
	if (fs_numcon.search() == 0)
	{	
        globals.DIALOGS.showWarningDialog("Aviso","Fecha inválida","Ok")
		return
	}
	else
	{
		if (fs_numcon.marca_cierre == 1)
		{
			globals.DIALOGS.showWarningDialog("Aviso","Mes Cerrado","Ok")
			return
		}
		
		var error = 0
		var $cant = forms.limbo_carga_det.controller.getMaxRecordIndex()
		for (var i = 1 ; i <= $cant ; i++)
		{
			forms.limbo_carga_det.controller.setSelectedIndex(i)
			
			if (forms.limbo_carga_det.cuentas_id == null)
			{
				error = 1
				globals.DIALOGS.showWarningDialog("Aviso","Existen cuentas sin completar","Ok")					
				break
			}
				
			if (forms.limbo_carga_det.importe_carga_debe != null && forms.limbo_carga_det.importe_carga_haber != null)
			{
				error = 1
				globals.DIALOGS.showWarningDialog("Aviso","Debe y Haber deben tener importes","Ok")
				break
			}
		}
		
		if (Math.abs(globals.gtotal_debe - globals.gtotal_haber) > 0.005)
		{
			error = 1
			globals.DIALOGS.showWarningDialog("Aviso","El Total del Debe no coincide con el Total del Haber","Ok")
		}
		
		if (error == 1)			
			globals.DIALOGS.showWarningDialog("Aviso","Asiento sin actualizar","Ok")			
		else
		{
			if (Math.abs(globals.gtotal_debe - ftotal) > 0.005)
			{
				var res = globals.DIALOGS.showWarningDialog('Aviso','El debe y haber coinciden, pero difieren del total ingresado, continua?','SI','NO')			    
				if (res == 'NO')
				{
					return
				}
			}
			// llamarla sólo si está tildado pesos/dólares
			//if (globals.gconversion_moneda != 0)
			//fConversionDolares()			
			numero       			= fs_numcon.limbo
			provisorio   			= fs_numcon.limbo
			tipo_actualizacion 		= globals.z_conf_asiento_normal
			hizo         			= globals.glegajo
			moneda_carga 			= fmoneda
			globals.gMonedaCarga 	= fmoneda
			total        			= globals.gtotal_debe
			moneda 					= "A"
			fConversionDolares()
			if (moneda_carga == 1)
			{
				moneda = "P"
			}
			else
			{
				moneda = "D"
			}
			fs_numcon.limbo++
			
			databaseManager.startTransaction()
			var estado = databaseManager.saveData()
			if (estado == false)
			{
				databaseManager.rollbackTransaction()
				databaseManager.revertEditedRecords()
				globals.DIALOGS.showWarningDialog("Aviso","No se actualizaron los datos","Ok")
				return
			}
			databaseManager.commitTransaction()
			globals.DIALOGS.showInfoDialog("Aviso","Asiento actualizado","Ok")
			databaseManager.setAutoSave(true)
            onShow()
		}
	}
}

/**
 * @properties={typeid:24,uuid:"D05F7EF2-9A0E-4518-97F4-D93E71997827"}
 */
function fConversionDolares()
{
	var vTotalD = 0
	var vTotalH = 0
	var $cant = forms.limbo_carga_det.controller.getMaxRecordIndex()
	
	for (var i = 1 ;i <= $cant ; i++)
	{
		forms.limbo_carga_det.controller.setSelectedIndex(i)
		
		if (forms.limbo_carga_det.importe_carga_debe == null || forms.limbo_carga_det.importe_carga_debe == 0)
		{
			var imp = forms.limbo_carga_det.importe_carga_haber.toFixed(2)*1
			forms.limbo_carga_det.columna = 'H'
		}	
		else
		{
			var imp = forms.limbo_carga_det.importe_carga_debe.toFixed(2)*1
			forms.limbo_carga_det.columna = 'D'
		}
		
		if (fmoneda == 1)//Pesos
		{
			var impodol = imp / dolar
			forms.limbo_carga_det.impodol = impodol.toFixed(2)*1
			forms.limbo_carga_det.importe = imp
			if (forms.limbo_carga_det.columna == 'D')
				vTotalD += forms.limbo_carga_det.impodol
			else
				vTotalH += forms.limbo_carga_det.impodol
		}
		else
		{
			var importe = imp * dolar
			forms.limbo_carga_det.importe = importe.toFixed(2)*1
			forms.limbo_carga_det.impodol = imp
			if (forms.limbo_carga_det.columna == 'D')
				vTotalD += forms.limbo_carga_det.importe
			else
				vTotalH += forms.limbo_carga_det.importe
		}
	}
	
	if (vTotalD != vTotalH)
	{
		var dif = vTotalD - vTotalH
		if (forms.limbo_carga_det.columna == 'H')
		{	
			if (fmoneda == 1)//Pesos
				forms.limbo_carga_det.impodol += dif
			else
				forms.limbo_carga_det.importe += dif
		}
		else
		{
			if (fmoneda == 1)//Pesos
				forms.limbo_carga_det.impodol -= dif
			else
				forms.limbo_carga_det.importe -= dif
		}
	}
}

/**
 * @properties={typeid:24,uuid:"5C43F810-2B11-466A-9785-4537BBB5265B"}
 */
function onAction_cancelar(event) {
	databaseManager.revertEditedRecords()
	onShow()
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"7C7D5669-697D-43BE-9098-5F3C576BF8D0"}
 */
function onAction_ordenar(event) {
	forms.limbo_carga_det.controller.sort('columna asc, cuentas_id asc')
}

/**
 * Handle changed data.
 *
 * @param {Object} oldValue old value
 * @param {Object} newValue new value
 * @param {JSEvent} event the event that triggered the action
 *
 * @returns {Boolean}
 *
 * @properties={typeid:24,uuid:"71E1C4E2-7A57-43AE-BA86-054AD45F9B58"}
 * @AllowToRunInFind
 */
function onDataChange_fecha(oldValue, newValue, event) {
	if (!newValue)
		return true
	dolar = globals.gBuscarCotizacion(fecha)
	var vAnio = fecha.getFullYear()
	var vMes = fecha.getMonth()+1
	/** @type {JSFoundSet<db:/contable/numcon>}*/
	var fs_numcon = databaseManager.getFoundSet('contable','numcon')

	fs_numcon.find()
	fs_numcon.anio 		= vAnio
	fs_numcon.mes 		= vMes
	fs_numcon.empresa 	= globals.gUservID
	if (fs_numcon.search() == 0)
	{	
        globals.DIALOGS.showWarningDialog("Aviso","Fecha inválida - no existe contador","Ok")
		return false
	}
	else
	{
		if (fs_numcon.marca_cierre == 1)
		{
			globals.DIALOGS.showWarningDialog("Aviso","Mes Cerrado","Ok")
			return false
		}
	}
	return true
}
